/**
 * 
 */
package com.jdy.haoduoai.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Environment;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.enums.PosterType;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.ycsj.goldmedalnewconcept.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

/**
 * @author zp 2016-12-13 上午11:03:27
 */
public class VoicePlayClickListener implements View.OnClickListener {

  public static final String TAG = "VoicePlayClickListener";

  public static boolean isPlaying = false;

  public static final String PREFIX = "voice_";

  private AnimationDrawable voiceAnimation = null;

  private final BaseAdapter adapter;

  public static VoicePlayClickListener currentPlayListener = null;

  private MediaPlayer mediaPlayer = null;

  private final SpeakForYouItem mSFYI;

  private final ImageView mCoverImg;

  private final ImageView mErrorImg;

  private final Activity mActivity;

  private final ProgressBar mProgressBar;

  private final ImageView mUnreadImg;

  private LeUser mLeUser;

  public VoicePlayClickListener(SpeakForYouItem sfyi, BaseAdapter adapter,
                                ImageView errorImg, ImageView coverImg, Activity activity,
                                ProgressBar pb, ImageView unreadImg) {

    this.mSFYI = sfyi;

    this.adapter = adapter;

    this.mErrorImg = errorImg;

    this.mCoverImg = coverImg;

    this.mActivity = activity;

    this.mProgressBar = pb;

    this.mUnreadImg = unreadImg;

    mLeUser = ((LeXiaoXiaoBanApp) activity.getApplication()).getUser();

    // downloadAudioFile();
  }

  private void downloadAudioFile() {

    new AsyncTask<String, Void, File>() {

      @Override
      protected File doInBackground(String... urls) {
        String urldisplay = urls[0];

        InputStream inputStream = null;

        OutputStream outputStream = null;

        File resultFile = new File(generateVoiceFilePath(urldisplay));

        if (resultFile.exists()) {

          mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {

              // stuff that updates ui
              mProgressBar.setVisibility(View.GONE);
            }
          });

          return resultFile;
        } else {
          mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
              // stuff that updates ui
              mProgressBar.setVisibility(View.VISIBLE);
            }
          });
        }

        try {
          URL url = new URL(urldisplay);

          HttpURLConnection urlConnection = (HttpURLConnection) url
              .openConnection();

          urlConnection.setRequestMethod("GET");
          // urlConnection.setDoOutput(true);

          urlConnection.connect();

          inputStream = urlConnection.getInputStream();

          outputStream = new FileOutputStream(resultFile);

          int read = 0;

          byte[] bytes = new byte[1024];

          while ((read = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
          }

        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          if (inputStream != null) {
            try {
              inputStream.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
          if (outputStream != null) {
            try {
              // outputStream.flush();
              outputStream.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
        return resultFile;
      }

      @Override
      protected void onPostExecute(File file) {
        String filePath = file.getAbsolutePath();

        if (!(new File(filePath).exists())) {
          return;
        }
      }

    }.execute(mSFYI.Src);
  }

  public void stopPlayVoice() {
    voiceAnimation.stop();
    mCoverImg.setImageResource(R.drawable.chatfrom_voice_playing);
    if (mediaPlayer != null) {
      try {
        mediaPlayer.stop();
        mediaPlayer.release();
      } catch (IllegalStateException e) {
        // TODO: handle exception
      }
    }
    isPlaying = false;
    adapter.notifyDataSetChanged();
  }

  public void playVoice() {
    try {
      new AsyncTask<String, Void, File>() {
        @Override
        protected File doInBackground(String... urls) {
          String urldisplay = urls[0];

          //return null;
          if (mSFYI.posterType != PosterType.Parent) {
            return null;
          }

          InputStream inputStream = null;
          OutputStream outputStream = null;
          File mFolder = new File(Environment.getExternalStorageDirectory()
              .getAbsolutePath() + "/haoduoai/");
          if (!mFolder.exists()) {
            mFolder.mkdir();
          }
          File resultFile = new File(generateVoiceFilePath(urldisplay));
          if (resultFile.exists()) {
            mActivity.runOnUiThread(new Runnable() {
              @Override
              public void run() {
                mProgressBar.setVisibility(View.GONE);
              }
            });
            return resultFile;
          } else {
            mActivity.runOnUiThread(new Runnable() {
              @Override
              public void run() {
                mProgressBar.setVisibility(View.VISIBLE);
              }
            });
          }

          try {
            URL url = new URL(urldisplay);
            HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();
            inputStream = urlConnection.getInputStream();
            outputStream = new FileOutputStream(resultFile);
            int read = 0;
            byte[] bytes = new byte[1024];
            while ((read = inputStream.read(bytes)) != -1) {
              outputStream.write(bytes, 0, read);
            }
          } catch (Exception e) {
            e.printStackTrace();
          } finally {
            if (inputStream != null) {
              try {
                inputStream.close();
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
            if (outputStream != null) {
              try {
                outputStream.close();
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
          return resultFile;
        }

        @Override
        protected void onPostExecute(File file) {
          if (file == null) {
            mProgressBar.setVisibility(View.GONE);
            mUnreadImg.setVisibility(View.GONE);
            mSFYI.hasRead = true;
            putReadStatus(mSFYI.id, 1);

            mediaPlayer = new MediaPlayer();
            try {
              mediaPlayer.setDataSource(mSFYI.Src);
              mediaPlayer.prepare();
              mediaPlayer
                      .setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                          if (mediaPlayer != null) {
                            mediaPlayer.release();
                            mediaPlayer = null;
                          }
                          stopPlayVoice();
                        }
                      });

              isPlaying = true;
              currentPlayListener = VoicePlayClickListener.this;
              mediaPlayer.start();
              showAnimation();
            } catch (Exception e) {
            }

            return;
          }

          String filePath = file.getAbsolutePath();

          if (!(new File(filePath).exists()) && mSFYI.posterType == PosterType.Parent) {
            Toast.makeText(mActivity, "文件不存在!", Toast.LENGTH_SHORT).show();
            return;
          }
          mProgressBar.setVisibility(View.GONE);
          mUnreadImg.setVisibility(View.GONE);
          mSFYI.hasRead = true;
          putReadStatus(mSFYI.id, 1);
          mediaPlayer = new MediaPlayer();
          if (mSFYI.posterType != PosterType.Parent) {
            filePath = mSFYI.Src;
          }
          try {
            mediaPlayer.setDataSource(filePath);
            mediaPlayer.prepare();
            mediaPlayer
                .setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                  @Override
                  public void onCompletion(MediaPlayer mp) {
                    if (mediaPlayer != null) {
                      mediaPlayer.release();
                      mediaPlayer = null;
                    }
                    stopPlayVoice();
                  }

                });

            isPlaying = true;
            currentPlayListener = VoicePlayClickListener.this;
            mediaPlayer.start();
            showAnimation();
          } catch (Exception e) {
          }
        }
      }.execute(mSFYI.Src);// URLEncoder.encode(mSFYI.Src,
                           // "utf-8").replace("%2F", "/")
    } catch (Exception e) {
      // TODO: handle exception
    }

  }

  // show the voice playing animation
  @SuppressLint("ResourceType")
  private void showAnimation() {
    // play voice, and start animation
    mCoverImg.setImageResource(R.anim.voice_from_icon);
    voiceAnimation = (AnimationDrawable) mCoverImg.getDrawable();
    voiceAnimation.start();
  }

  @Override
  public void onClick(View v) {
    if (isPlaying) {
      currentPlayListener.stopPlayVoice();
    }

    playVoice();
  }

  private void putReadStatus(final int id, final int audio_read) {
    new CustomAsyncTask(mActivity, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put("sno", mLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put("audio_read", audio_read);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/member/history/sound/" + id, param_,
            HttpUtils.TAG_PUT_REQUEST);
      }
    }).execute();
  }

  private String generateVoiceFilePath(String url) {
    String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    String[] stringArray = url.split("/");
    String fileName = stringArray[stringArray.length - 1];
    path += "/haoduoai/" + PREFIX + fileName;
    return path;
  }

}
